<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 * 
 * 创建时间：2021-11-17 20:46
 *
 * 项目：rm  -  $  - totalitemHelper.php
 *
 * 作者：liwei 
 */

namespace modules\levfm\table\form\FormData;

use Lev;
use lev\helpers\cacheFileHelpers;
use modules\levfm\table\LevfmForms;
use modules\levfm\widgets\inputs\inputsFormWidget;

!defined('INLEV') && exit('Access Denied LEV');


class totalitemHelper
{

    public static $formInfo   = null;
    public static $totalField = null;

    public static $votenums   = null;//大力支持数据

    public static $opInfo       = null;//通过数据ID 判断是否编辑

    public static $totalitem  = null;

    public static function init($formInfo, $opInfo) {
        static::$opInfo = $opInfo;

        static::$votenums = json_decode(Lev::GPv('votenums'), true) ?: [];

        static::$formInfo   === null  && static::$formInfo = $formInfo;
        static::$totalField === null  && (static::$totalField = LevfmForms::getSettingsTotalitem($formInfo['settings'])) &&
        static::$totalField = array_flip(static::$totalField);

        static::$totalitem === null &&
        static::$totalitem = static::getTotalitems(static::$formInfo, 0);
    }

    public static function total($input, $value) {
        if (isset(static::$totalField[$input['inputname']])) {
            $totalKey = 0;
            if (inputsFormWidget::isSelectOnly($input)) {
                $totalKey = $value;
            }elseif (inputsFormWidget::isSelectInput($input)) {
                $options = inputsFormWidget::getSelectItem($input);
                isset($options[$value]) && $totalKey = $value;
            }
            $num = inputsFormWidget::isNumberInput($input) ? floatval($value) : 1;
            !empty(static::$votenums[$input['inputname']][$totalKey]) && is_numeric(static::$votenums[$input['inputname']][$totalKey]) &&
            $num += static::$votenums[$input['inputname']][$totalKey];
            static::setTotalKeynum($input, $totalKey, $num);
        }
    }
    public static function setTotalKeynum($input, $totalKey, $num) {
        if (is_array($totalKey)) {
            foreach ($totalKey as $v) {
                static::setTotalKeynum($input, $v, $num);
            }
        }else {
            $dates = ['total'];
            //LevfmForms::isTotalitemDays(static::$formInfo['settings']) &&
            $dates[] = date('Ymd', Lev::$app['timestamp']).'';
            foreach ($dates as $date) {
                if (isset(static::$totalitem[$date][$input['inputname']][$totalKey])) {
                    (empty(static::$opInfo['datas'][$input['inputname']]) || LevfmForms::isTotalitemRepeat(static::$formInfo['settings'])) &&
                    static::$totalitem[$date][$input['inputname']][$totalKey] += $num;
                } else {
                    static::$totalitem[$date][$input['inputname']][$totalKey] = $num;
                }
            }
        }
    }

    public static function setTotalitem()
    {
        if (static::$totalitem) {
            if ($max = LevfmForms::isTotalitemDays(static::$formInfo['settings'])) {
                $totals['total'] = static::$totalitem['total'];
                $totals += array_slice(static::$totalitem, -$max, null, true);
            }else {
                $totals['total'] = static::$totalitem['total'];
            }
            static::$totalitem = $totals;
            LevfmForms::update(['totalitem' => Lev::setSettings(static::$totalitem)], ['id' => static::$formInfo['id']]);
        }

    }

    public static function getTotalItemDaysBtn($formInfo) {
        $result[] = ['name'=>'完全统计', 'day'=>null];
        if ($max = LevfmForms::isTotalitemDays($formInfo['settings'])) {
            $result[] = ['name'=>'今日', 'day'=>0];
            $result[] = ['name'=>'昨日', 'day'=>1];
            $max > 1 && $result[] = ['name'=>'近两日', 'day'=>2];
            $max > 2 && $result[] = ['name'=>'近三日', 'day'=>3];
            //$max > 3 && $result[] = ['name'=>'近四日', 'day'=>4];
        }
        return $result;
    }

    public static function addtimeTotal($formInfo) {
        $addtime = $formInfo['addtime'];
        $tempNum = LevfmForms::getTotalitemTempnum($formInfo['settings']);
        return ($num = ceil((Lev::$app['timestamp'] - $addtime)/24 * $tempNum)) < 50 ? 50 : $num;
    }

    public static function getTotalitems(array $formInfo, $date = 'total', $day = null)
    {
        $totalitems = Lev::getSettings($formInfo['totalitem']);
        if (!$date) {
            return $totalitems;
        }
        if (is_numeric($day)) {
            switch ($day) {
                case 0 : $date = date('Ymd', Lev::$app['timestamp']); break;
                case 1 : $date = date('Ymd', Lev::$app['timestamp'] - 24*3600); break;
                default:
                    $totalitem = $totalitems['total'];
                    if (count($totalitems)-1 > $day) {
                        unset($totalitems['total']);

                        $_totalitem = array_slice($totalitems, -$day);
                        $totalitem = $_totalitem[0];
                        for ($i=1; $i<$day; $i++) {
                            foreach ($_totalitem[$i] as $k => $v) {
                                if (empty($totalitem[$k])) {
                                    $totalitem[$k] = $v;
                                }else {
                                    foreach ($v as $k2 => $v2) {
                                        isset($totalitem[$k][$k2]) || $totalitem[$k][$k2] = 0;
                                        $totalitem[$k][$k2] += $v2;
                                    }
                                }
                            }
                        }
                    }
                    return $totalitem;
                    break;
            }
        }

        return empty($totalitems[$date]) ? $totalitems['total'] : $totalitems[$date];
    }

    public static function getItemTempnum($formInfo, $inputs = []) {
        $ttnum = 0;
        if ($tempNum = LevfmForms::getTotalitemTempnum($formInfo['settings'])) {
            if (isset($formInfo['_day']) && is_numeric($formInfo['_day'])) {
                $ttnum = !$formInfo['_day']
                    ? ceil((Lev::$app['timestamp']-Lev::getDayStartTime())/24) * $tempNum
                    : 3600 * $tempNum * $formInfo['_day'];
            }else {
                $num = static::addtimeTotal($formInfo);
                $ttnum = ceil($num / static::getTotalOptionsCache($formInfo['id'], $inputs));
            }
        }
        return ceil($ttnum);
    }

    public static function getTotalOptionsCache($formid, $inputs, $force = false) {
        $key = 'getTotalOptionsCache'.$formid;
        if (!$force && $total = cacheFileHelpers::getc($key)) {
            return $total;
        }else {
            $total = static::getTotalOptions($inputs);
            cacheFileHelpers::setc($key, $total);
        }
        return $total;
    }
    public static function getTotalOptions($inputs = null) {
        $total = 0;
        foreach ($inputs as $v) {
            ($options = inputsFormWidget::getSelectItem($v)) && $total += count($options);
        }
        return $total ?: 1;
    }
}